export const isMediaRecorder = () => {
  if (
    !navigator.mediaDevices ||
    !navigator.mediaDevices.getUserMedia ||
    !MediaRecorder
  ) {
    return false;
  }
  return true;
};

export function isMobile(): boolean {
  return "ontouchstart" in document.documentElement;
}

export function getElement(el: HTMLElement | string) {
  return (
    typeof el === "string" ? document.querySelector(el) : el
  ) as HTMLElement;
}

export const isObject = (value: any) => {
  return value && typeof value === "object" && !Array.isArray(value);
};

export const mergeDeep = (target: any = {}, source: any = {}) => {
  const output = Object.assign({}, target);
  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach((key) => {
      if (isObject(source[key])) {
        if (!(key in target)) Object.assign(output, { [key]: source[key] });
        else output[key] = mergeDeep(target[key], source[key]);
      } else {
        Object.assign(output, { [key]: source[key] });
      }
    });
  }
  return output;
};

export const createElement = (eleName: string, className?: string) => {
  if (!className) return;
  let ele = document.querySelector(className);
  if (!ele) {
    ele = document.createElement(eleName);
    ele.classList.add(className);
  }
  return ele;
};

export const getMimeType = () => {
  let mimeType = ""
  if (typeof MediaRecorder.isTypeSupported === 'function') {
    if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
      mimeType = 'video/webm;codecs=vp9';
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
      mimeType = 'video/webm;codecs=h264';
    } else if (MediaRecorder.isTypeSupported('video/webm')) {
      mimeType = 'video/webm';
    } else if (MediaRecorder.isTypeSupported('video/mp4')) {
      //Safari 14.0.2 has an EXPERIMENTAL version of MediaRecorder enabled by default
      mimeType = 'video/mp4';
    }
  }
  return mimeType;
}